import { defineStore } from "pinia";
import { Local, Session } from "@/utils/storage";
import { getInfo } from "@/api/login";
import { userBasicInfoKey, userInfoKey } from "@/utils/auth";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore("userInfo", {
  state: (): UserInfosState => ({
    userInfos: {
      userId: 0,
      userName: "",
      avatar: "",
      time: 0,
      roles: [],
      authBtnList: []
    }
  }),
  actions: {
    async setUserInfos() {
      // 存储用户信息到浏览器缓存
      if (Session.get(userInfoKey)) {
        this.userInfos = Session.get(userInfoKey);
      } else {
        this.userInfos = <UserInfos>await this.getApiUserInfo();
      }
    },
    /**
     * 更新头像
     */
    updateAvatar(avatar: string) {
      this.userInfos.avatar = avatar;
      Session.set(userInfoKey, this.userInfos);
    },
    // 模拟接口数据
    // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
    async getApiUserInfo() {
      return new Promise(resolve => {
        getInfo().then(res => {
          const { permissions, roles, user } = res.data;
          // 用户信息模拟数据
          const userInfos = {
            userId: user.id,
            nickName: user.nickName,
            userName: user.userName,
            avatar: user.avatar,
            time: new Date().getTime(),
            roles: roles,
            dept: {
              deptName: user?.dept?.deptName,
              id: user?.dept?.id
            },
            authBtnList: permissions
          };
          // 把全量信息存到session 以便刷新页面时重新获取
          Session.set(userInfoKey, userInfos);
          // 用户信息放到localStorage 避免重复获取
          Local.set(userBasicInfoKey, userInfos);
          resolve(userInfos);
        });
      });
    }
  }
});
